import logging

import pytest

from resource.pom.settings import Settings
from resource.pom.system_ui import SystemUI
from utils.manager import Images


class Test:
    app = Settings
    system_ui = SystemUI

    @pytest.mark.parametrize('setup_teardown', [app.bundle_name], indirect=True)
    def test(self, setup_teardown, device):
        logging.info('步骤1.点击设置应用')
        device.start_ability(self.app.bundle_name, self.app.ability_name)
        logging.info('预期结果1.进入设置界面')
        device.assert_current_window(self.app.window_name)

        logging.info('步骤2.点击隐私')
        device.click(*self.app.privacy_item)
        logging.info('预期结果2.进入隐私')
        device.refresh_layout()
        device.assert_text_exist('定位服务')

        logging.info('步骤3.点击定位服务')
        device.click_element(device.get_element_by_text('定位服务'))
        logging.info('预期结果3.进入定位服务')
        device.refresh_layout()
        device.assert_text_exist('访问我的位置信息')
        device.assert_type_exist('Toggle')

        logging.info('步骤4.点击开启或关闭位置按钮')
        toggle = device.get_element_by_type('Toggle')
        element_area = device.get_element_area(toggle)
        switch_status0 = toggle.get('checked')
        # 打开位置开关
        if switch_status0 == 'false':
            device.click_element(toggle)
            device.wait(2)
        dw_on = device.save_snapshot_to_local('location_on.jpeg')
        dw_on = Images.crop_picture(dw_on, *element_area)
        # 状态栏
        statusbar_pic = device.save_snapshot_to_local('statusbar.jpeg')
        statusbar_pic = Images.crop_picture(statusbar_pic, *self.system_ui.statusbar_area)
        device.click_element(toggle)
        device.wait(2)
        dw_off = device.save_snapshot_to_local('location_off.jpeg')
        dw_off = Images.crop_picture(dw_off, *element_area)

        logging.info('预期结果4.可开启关闭位置按钮，开启时通知栏显示位置图标，位置定位关闭时通知栏位置图标消失')
        on_similarity = Images.compare_image_similarity(dw_on, self.app.switch_on)
        off_similarity = Images.compare_image_similarity(dw_on, self.app.switch_off)
        assert on_similarity > off_similarity, '界面上显示位置开关未打开'

        is_in = Images.is_image_in_image(self.system_ui.locate_icon, statusbar_pic)
        assert is_in, '状态栏没有显示定位图标'

        off_similarity = Images.compare_image_similarity(dw_off, self.app.switch_off)
        on_similarity = Images.compare_image_similarity(dw_off, self.app.switch_on)
        assert off_similarity > on_similarity, '界面上显示位置开关未关闭'
